# -*- coding: utf-8 -*-
"""
Module Description: 装饰器相关
Date: 2020/08/12
Author: sxj
"""

from functools import wraps
import pyshare.framework.distribute.mutex as mutex
from pyshare.utils.list_utils import get_orderly_list
from framework.firefly_dc import runtime_logger as log
from pyshare.distributed.scheduler_lock_define import SchedulerExecuteLock


def scheduler_execute_lock(overtime_sec=1):
    """
    定时任务调用方法时加锁
    :param overtime_sec: 锁超时时间(s)
    :return:
    """
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kw):
            # 锁的key的定义
            func_name = func.__name__
            args_list = list(args)
            # 参数为self或cls则不加入key中
            if 'self' in func.__code__.co_varnames or 'cls' in func.__code__.co_varnames:
                args_list = args_list[1:]

            # 将参数及参数内dict和set排序，确保唯一性
            args_list.extend(kw.values())
            args_list = get_orderly_list(args_list)
            args_str_list = [str(i) for i in args_list]
            args_str = '_'.join(args_str_list)

            # 拼接得到锁的key
            lock_key = func_name if not args_str else func_name + '-' + args_str

            # 加锁并执行
            with mutex.KeyMutex(SchedulerExecuteLock.MU_SCHEDULER_EXE.format(func_name_param=lock_key),
                                overtime_sec=overtime_sec, try_lock_timeout=0.05) as mu:
                if mu.acquire_lock_success:
                    log.warning("SchedulerExecuteLockLog: func_name:{},scheduler_lock_name:{}".format(
                        func_name, SchedulerExecuteLock.MU_SCHEDULER_EXE.format(func_name_param=lock_key)
                    ))
                    return func(*args, **kw)

                log.warning("SchedulerExecuteLockError: func_name:{},scheduler_lock_name:{}".format(
                    func_name, SchedulerExecuteLock.MU_SCHEDULER_EXE.format(func_name_param=lock_key)
                ))
                return {'status': False}
        return wrapper
    return decorator
